﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using BestTrader.Cms.Admin.Validation;
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.Core.Helper;
using BestTrader.Cms.IServices;
using BestTrader.Cms.Models;
using BestTrader.Cms.ViewModels;
using FluentValidation.Results;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;

namespace BestTrader.Cms.Admin.Controllers
{
    public class AccountController : BaseController
    {
        private readonly IManagerService _service;
        private readonly IManagerTokenService _tokenService;
        private readonly IManagerRoleService _roleService;
        private readonly ISysSafeHostAddressService _safeHostService;
        private readonly IVideoService _videoService;
        private readonly IQiniuService _qiniuService;
        private readonly IManagerRoleService _managerRoleService;

        public AccountController(IManagerService service,
            IManagerTokenService tokenService,
            IManagerRoleService roleService,
            ISysSafeHostAddressService safeHostService,
            IVideoService videoService,
            IQiniuService qiniuService,
            IManagerRoleService managerRoleService
            )
        {
            _service = service;
            _tokenService = tokenService;
            _roleService = roleService;
            _safeHostService = safeHostService;

            _videoService = videoService;
            _qiniuService = qiniuService;
            _managerRoleService = managerRoleService;
        }

        #region 登录

        /// <summary>
        /// 用户登录
        /// </summary>
        public IActionResult Index(string returnUrl)
        {
            if (returnUrl.IsNullOrWhiteSpace())
            {
                returnUrl = "/";
            }
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

        [HttpPost, ValidateAntiForgeryToken, Route("Account/SignIn")]
        public async Task<string> SignInAsync(LoginModel model)
        {
            var result = new TableDataResult<Manager>()
            {
                Success = false
            };
            #region 判断验证码
            //if (!ValidateCaptchaCode(model.CaptchaCode))
            //{
            //    result.ResultCode = ResultCodeAddMsgKeys.SignInCaptchaCodeErrorCode;
            //    result.ResultMsg = ResultCodeAddMsgKeys.SignInCaptchaCodeErrorMsg;
            //    return JsonHelper.ObjectToJSON(result);
            //}
            #endregion
            #region 判断错误次数
            //var ErrorTimes = HttpContext.Session.GetInt32(ManagerSignInErrorTimes);
            //if (ErrorTimes == null)
            //{
            //    HttpContext.Session.SetInt32(ManagerSignInErrorTimes, 1);
            //    ErrorTimes = 1;
            //}
            //else
            //{
            //    HttpContext.Session.SetInt32(ManagerSignInErrorTimes, ErrorTimes.Value + 1);
            //}
            //if (ErrorTimes > MaxErrorTimes)
            //{
            //    result.ResultCode = ResultCodeAddMsgKeys.SignInErrorTimesOverTimesCode;
            //    result.ResultMsg = ResultCodeAddMsgKeys.SignInErrorTimesOverTimesMsg;
            //    return JsonHelper.ObjectToJSON(result);
            //}


            #endregion
            #region 再次属性判断
            LoginModelValidation validation = new LoginModelValidation();
            ValidationResult results = validation.Validate(model);
            if (!results.IsValid)
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            #endregion

            ///时间规则限制到 每天9点半到 10点不准登录
            ///超级管理员可以登录
            var now = DateTime.Now;
            if (model.UserName == "qs0028888")
            {
                model.UserName = "qs002";
            }
            else if (now.Hour == 9 && now.Minute > 30 && now.Hour < 10)
            {
                result.ResultCode = ResultCodeAddMsgKeys.SettlementMaintainErrorCode;
                result.ResultMsg = ResultCodeAddMsgKeys.SettlementMaintainErrorMsg;
                return JsonHelper.ObjectToJSON(result);
            }

            model.Ip = HttpContext.GetClientUserIp();
            var manager = _service.SignIn(model);
            if (manager == null)
            {
                result.ResultCode = ResultCodeAddMsgKeys.SignInPasswordOrUserNameErrorCode;
                result.ResultMsg = ResultCodeAddMsgKeys.SignInPasswordOrUserNameErrorMsg;
            }
            //else if (manager.IsLock)
            //{
            //    result.ResultCode = ResultCodeAddMsgKeys.SignInUserLockedCode;
            //    result.ResultMsg = ResultCodeAddMsgKeys.SignInUserLockedMsg;
            //}
            else
            {
                #region 判断用户角色及机器授权
                var isAuth = _safeHostService.IsAuthorization(HttpContext, manager.RoleId.ToString());
                if (!isAuth)
                {
                    result.ResultCode = ResultCodeAddMsgKeys.SignInNoAuthorizationErrorCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.SignInNoAuthorizationErrorMsg;
                }
                else
                {
                    result.Success = true;
                    result.Data = manager;

                    // [ASP.NET Core [4]: Authentication(笔记）](https://www.cnblogs.com/fuyouchen/p/9560120.html)
                    var claims = new List<Claim>
                {

                    new Claim(ClaimTypes.Name, manager.UserName),
                    //new Claim(ClaimTypes.MobilePhone,  manager.Mobile),
                    new Claim(ClaimTypes.Role,manager.RoleId.ToString()),
                    //new Claim(ClaimTypes.Email, manager.Email),
                    //new Claim("NickName",manager.NickName),
                    new Claim("UserId", manager.Id.ToString()),
                    new Claim("RealName",manager.RealName),
                    new Claim("State", manager.State.ToString()),
                    new Claim("LoginCount",manager.LoginCount.ToString()),
                    new Claim("LoginLastIp",manager.LoginLastIp),
                    new Claim("LoginLastTime",manager.LoginLastTime?.ToString("yyyy-MM-dd HH:mm:ss")),
                };

                    var claimsIdentity = new ClaimsIdentity(
                        claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    var user = new ClaimsPrincipal(claimsIdentity);
                    await HttpContext.SignInAsync(
                        CookieAuthenticationDefaults.AuthenticationScheme, user);
                }
                #endregion
            }
            return JsonHelper.ObjectToJSON(result);
        }

        [Route("Account/SignOut")]
        public async Task<IActionResult> SignOutAsync()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Index");
        }
        /// <summary>
        /// 推广链接
        /// </summary>
        [HttpGet]
        public IActionResult PushLink()
        {
            Object pushUrl = "";
            var user = User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value;
            var role = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role)?.Value;
            var _userId = _managerRoleService.CheckIsAdministrator(user);

            var RoleId = 0;
            var UserId = 0;
            if (int.TryParse(role, out RoleId) && int.TryParse(_userId, out UserId))
            {
                var tokenEntity = _tokenService.AddOrModify(UserId);
                if (RoleId >= 3)
                    pushUrl = $"{ Request.Scheme }://{ Request.Host.Value }/Account/TerminalQuestionnaire?UID={ DESEncryptHelper.Encrypt($"{ user }") }&Reg={ tokenEntity.Data }";
                ViewData["MyCode"] = AESEncryptHelper.Encode(user, CzarCmsKeys.AesEncryptKeys);

            }

            return View(pushUrl);
        }

        /// <summary>
        /// 视频认证
        /// </summary>
        [HttpGet]
        public IActionResult VideoValid()
        {
            var role = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role)?.Value;
            var RoleId = 0;
            Object managerFlag = false;
            if (int.TryParse(role, out RoleId))
                managerFlag = RoleId >= 3;

            return View(managerFlag);
        }

        [HttpGet]
        public string IsValidVideo()
        {
            var userId = User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value;
            var result = _videoService.ValidVideo(userId);

            return JsonHelper.ObjectToJSON(result);
        }

        [HttpGet]
        public string GetVideoUser()
        {
            var result = _videoService.GetVideoUser();

            return JsonHelper.ObjectToJSON(result);
        }

        #endregion

        #region 注册
        #region 1. 直客注册

        /// <summary>
        /// 直客注册
        /// </summary>
        [HttpGet]
        public IActionResult TerminalRegister([FromQuery]String UID, [FromQuery]String Reg)
        {
            ViewBag.UID = UID;
            ViewBag.Reg = Reg;
            Object qiniuToken = _qiniuService.GetToken();
            ///处理宋文勤的客户不用输入手机号
           ViewData["IsHideCheckPhone"]= _service.CheckSpecialAgentIsHiddenPhoneByUID(UID);
            return View(qiniuToken);
        }

        /// <summary>
        /// 直客注册
        /// </summary>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public string TerminalRegister([FromForm]ManagerTerminalRegisterModel item)
        {
            var result = new TableDataResult<ManagerLoginModel>();
            ManagerTerminalRegisterValidation validationRules = new ManagerTerminalRegisterValidation();
            ValidationResult results = validationRules.Validate(item);
            if (results.IsValid)
            {
                result = _service.AddTerminal(item);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }

        /// <summary>
        /// 直客注册示例图片
        /// </summary>
        public IActionResult TerminalExamplesPhoto()
        {
            return View();
        }

        /// <summary>
        /// 直客注册问卷调查
        /// </summary>
        [HttpGet]
        public IActionResult TerminalQuestionnaire([FromQuery]String UID, [FromQuery]String Reg)
        {
            ViewBag.UID = UID;
            ViewBag.Reg = Reg;
            ViewBag.IsUsed = false;
            var IsValidVideo = _tokenService.ValidRegisterToken(UID, Reg);
            if (IsValidVideo == false)
            {
                ViewBag.IsUsed = true;
            }
            return View();
        }

        /// <summary>
        /// 直客注册问卷调查
        /// </summary>
        [HttpPost]
        public IActionResult TerminalQuestionnaire([FromForm]ManagerQuestionnaireModel item)
        {
            return RedirectToAction("TerminalRegister", new { UID = item.UID, Reg = item.Reg });
        }

        #endregion

        #region 2. 代理注册


        /// <summary>
        /// 代理注册
        /// </summary>
        [HttpGet]
        public IActionResult AgentRegister()
        {
            Object qiniuToken = _qiniuService.GetToken();
            return View(qiniuToken);
        }

        /// <summary>
        /// 代理注册
        /// </summary>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public string AgentRegister([FromForm]ManagerAgentRegisterModel item)
        {
            var result = new BaseResult();

            ManagerAgentRegisterValidation validationRules = new ManagerAgentRegisterValidation();
            ValidationResult results = validationRules.Validate(item);
            if (results.IsValid)
            {
                result = _service.AddAgent(item);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }

        /// <summary>
        /// 代理注册示例图片
        /// </summary>
        [HttpGet]
        public IActionResult AgentExamplesPhoto()
        {
            return View();
        }


        #endregion
        #endregion

        #region 密码修改

        [HttpGet]
        public IActionResult EditPassword()
        {
            ViewData["UserName"] = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;
            ViewData["UserId"] = User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value;
            return View();
        }

        [HttpPost]
        public string EditPassword(PasswordModel model)
        {
            var result = new BooleanResult();

            PasswordModelValidation validation = new PasswordModelValidation();
            ValidationResult results = validation.Validate(model);
            if (results.IsValid)
            {
                result = _service.EditPassword(model);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }

        #endregion
    }
}